package com.stand.hardcode.manager;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServletRequest;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.users.User;
import com.stand.hardcode.database.PMF;
import com.stand.hardcode.entity.StandUser;
import com.stand.hardcode.exception.UsernameTakenException;
import com.stand.hardcode.util.Hash;
import com.stand.hardcode.util.RequestAttributes;

public class UserManager {
	
	public static boolean IsLoggedIn(HttpServletRequest req){
		
		if(req.getSession().getAttribute(RequestAttributes.CURRENT_USER) != null){
			return true;
		}
		else{
			return false;
		}
		
	}
	
	public static void StoreUser(StandUser u) throws UsernameTakenException{
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			StandUser qry = pm.getObjectById(StandUser.class, u.getKey());
		}catch(JDOObjectNotFoundException e){
			try {
	            pm.makePersistent(u);
	        } finally {
	            pm.close();
	        }
			return;
		}
		
		//if object found
		throw new UsernameTakenException();
		
	}
	
	public static boolean ExistsUser(String email){
		
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Key key = KeyFactory.createKey(StandUser.class.getSimpleName(), email);
		try {
			StandUser qry = pm.getObjectById(StandUser.class, key);
			pm.close();
			return true;
		}catch(JDOObjectNotFoundException e){
			pm.close();
			return false;
	     }
			
		
	}
	
	public static StandUser RetrieveUser(Key key) throws JDOObjectNotFoundException{
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			StandUser qry = pm.getObjectById(StandUser.class, key);
			StandUser detached = pm.detachCopy(qry);
			pm.close();
			return detached;
		 }catch(JDOObjectNotFoundException e){
			 pm.close();
			 return null;
	     }
		
		
	}
	
	public static void UpdateUser(StandUser u){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
            pm.makePersistent(u);
        } finally {
            pm.close();
        }
	}

	public static void DeleteUser(StandUser u) {
		
		PersistenceManager pm = PMF.get().getPersistenceManager();
		StandUser qry = pm.getObjectById(StandUser.class, u.getKey());
		pm.deletePersistent(qry);
		pm.close();
	}
	
	
	
}
